﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

using ERPStore.Extensions;

using CloudSoft.Extensions;

using System.Xml;

namespace ERPStore.Exporter.Providers
{
	public class TwengaExport : ExportBase
	{
		XDocument m_Document;

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.AllowMissingDefaultImage = false;
			settings.AllowNotSellable = false;
			settings.AllowNullLongDescription = true;
			settings.AllowNullShortDescription = true;
			settings.AllowStockEmpty = false;
			settings.AllowZeroSalePrice = false;
			settings.FileName = "twenga.xml";
		}

		public override string Name
		{
			get { return "Twenga"; }
		}

		public override string LeadSourceId
		{
			get { return "399F815C-E82F-4E84-9291-1BAB90333812"; }
		}

		public override void CreateDocument()
		{
			m_Document = new XDocument(new XDeclaration("1.0", "UTF-8", null));
			var root = new XElement("catalog");
			m_Document.Add(root);
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStock)
		{
			var description = product.ShortDescription ?? product.LongDescription ?? product.PageTitle ?? product.Title;
			var url = BuildEncryptedProductUrl(LeadSource, product);
			var price = ToCurrency(product.BestPrice.ValueWithTax,true).Replace(",", ".");
			var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.First(i => i.Country == ERPStore.Models.Country.FRA);
			decimal deliveryCost = deliveryCountry.ShippingFeeAmount;
			if (product.Shipping.Strategy == ERPStore.Models.FeeTransportStrategy.FixedPrice)
			{
				deliveryCost = new ERPStore.Models.Price(product.Shipping.FixedPrice, product.DefaultTaxRate).ValueWithTax;
			} else if (product.BestPrice.Value > deliveryCountry.MinimalFreeOfCarriageAmount)
			{
				deliveryCost = 0;
			}
			var image_url = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			var condition = "New";
			var category = GetDeepCategoryName(product);

			var item = new XElement("product"
						, new XElement("mechant_id", product.Code)
						, new XElement("product_url", url)
						, new XElement("designation", CapitalizeWords(product.PageTitle ?? product.Title))
						, new XElement("price", price)
						, new XElement("category", category)
						, new XElement("image_url", image_url)
						, new XElement("description", description)
						, new XElement("shipping_cost", ToCurrency(deliveryCost, true).Replace(",","."))
						, new XElement("condition","0")
						, new XElement("product_type", "1")
						);

			if (productStock != null)
			{
				item.Add(new XElement("in_stock", (productStock.PhysicalStock > 0) ? "Y" : "N"));
				item.Add(new XElement("availability", productStock.AvailableStock.ToString()));
			}

			if (product.Brand != null)
			{
				item.Add(new XElement("brand", product.Brand.Name));
			}

			if (!product.ManufacturerPartNumber.IsNullOrTrimmedEmpty())
			{
				item.Add(new XElement("manufacturer_id", product.ManufacturerPartNumber));
			}

			if (!product.Gtin.EAN.IsNullOrTrimmedEmpty())
			{
				item.Add(new XElement("upc_ean", product.Gtin.EAN));
			}

			if (product.Stats != null && product.Stats.SaleRate.HasValue)
			{
				item.Add(new XElement("rank", Math.Max(1, Math.Ceiling(product.Stats.SaleRate.Value))));
			}

			if (deliveryCost == 0)
			{
				item.Add(new XElement("stock_detail", "Free shipping"));
			}


			m_Document.Root.Add(item);
		}

		public override void SaveDocument()
		{
			var xmlWriterSettings = new XmlWriterSettings()
			{
				CheckCharacters = false,
				Indent = true,
			};
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			using (var xmlWriter = XmlWriter.Create(fileName, xmlWriterSettings))
			{
				m_Document.Save(xmlWriter);
				xmlWriter.Flush();
				xmlWriter.Close();
			}
		}

		public override void Dispose()
		{
			m_Document = null;
		}

		protected override string GetDeepCategoryName(ERPStore.Models.Product product)
		{
			var path = new List<string>();
			var c = product.Category;
			while (true)
			{
				if (c != null)
				{
					path.Add(c.Name);
				}
				else
				{
					break;
				}
				c = c.Parent;
			}
			if (path.IsNullOrEmpty())
			{
				return string.Empty;
			}

			path.Reverse();
			return path.JoinString(" > ");
		}

	}
}
